package com.autumn.controller;

import com.autumn.entities.CommonResult;
import com.autumn.entities.Payment;
import com.autumn.services.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 123
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/create")
    public CommonResult<Integer> create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);

        if (result > 0) {
            return new CommonResult<>(200, "创建成功", result);
        } else {
            return new CommonResult<>(444, "创建失败", result);
        }
    }


    @GetMapping("/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);

        if (paymentById == null) {
            return new CommonResult<>(444, "根据id获取支付信息失败", null);
        } else {
            return new CommonResult<>(200, "根据id获取支付信息成功:" + serverPort, paymentById);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();

        services.forEach(s -> {
            log.info("service name:{}", s);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");

        for (ServiceInstance instance : instances) {
            log.info("{}\t{}\t{}\t{}\t", instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getUri());
        }

        return discoveryClient;
    }
}
